package com.infinit.selfhelp.common.utils

import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.FragmentActivity

/**
 *  requestPermission(arrayOf("android.permission.READ_MEDIA_IMAGES", "android.permission.READ_MEDIA_AUDIO")) {
 *  }
 * */
fun FragmentActivity.requestPermission(
    permissions: Array<String>,
    callBack: (granted: Boolean) -> Unit,
) {
    lateinit var requestMultiplePermissions: ActivityResultLauncher<Array<String>>
    requestMultiplePermissions = this.activityResultRegistry.register(
        "registry",
        ActivityResultContracts.RequestMultiplePermissions(),
    ) { permissions ->
        callBack(!permissions.containsValue(false))
        requestMultiplePermissions.unregister() // unregister()是关键，由于不是在onCreate方法中注册的，不加上它，在使用时会发生重复监听的情况。
    }
    requestMultiplePermissions.launch(permissions)
}
